﻿using System;
using BusinessBingo.CommandHandlers.Base;
using BusinessBingo.CommandHandlers.Interfaces;
using BusinessBingo.CommandHandlers.Results;
using BusinessBingo.Commands;
using BusinessBingo.Data.Filter;
using BusinessBingo.Data.Interfaces;
using BusinessBingo.Model;
using BusinessBingo.Model.Interfaces;

namespace BusinessBingo.CommandHandlers
{
    public class CheckForUrlUniquenessCommandHandler :
        BaseCommandHandler,
        ICheckForUrlUniquenessCommandHandler
    {
        private IGroupRepository _groupRepository;

        public CheckForUrlUniquenessCommandHandler(
            IValidationState validationState,
            IUnitOfWork unitOfWork,
            IGroupRepository groupRepository)
            : base(validationState, unitOfWork)
        {
            this._groupRepository = groupRepository;
        }

        public CheckForUrlUniquenessCommandHandlerResult Execute(CheckForUrlUniquenessCommand checkForUrlUniquenessCommand)
        {
            CheckForUrlUniquenessCommandHandlerResult result = new CheckForUrlUniquenessCommandHandlerResult();

            if(checkForUrlUniquenessCommand == default(CheckForUrlUniquenessCommand))
                throw new ArgumentNullException("CheckForUrlUniquenessCommand");

            if(string.IsNullOrWhiteSpace(checkForUrlUniquenessCommand.UrlToCheck) == true)
                this._validationState.AddError<CheckForUrlUniquenessCommand>(x => x.UrlToCheck, ErrorTypes.Empty);

            if (this._validationState.IsValid == false)
                return result;

            result.IsUnique = true;

            GroupFilter filter = new GroupFilter();
            filter.WithUrl = checkForUrlUniquenessCommand.UrlToCheck;

            int count = this._groupRepository.GetItemsCount(filter);

            if (count > 0)
                result.IsUnique = false;

            result.Succeeded = true;
            return result;
        }
    }
}